<template>
  <div class="home container" :class="{mobile:mobile}">
    <el-row>
      <el-button
        type="primary"
        plain
        size="small"
        icon="el-icon-back"
        v-if="parent != -1"
        @click="back"
      >返回首页</el-button>
      <el-button type="primary" plain size="small" @click="add()">新增</el-button>
      <el-button
        type="primary"
        plain
        size="small"
        @click="showTools=!showTools"
      >{{showTools?'隐藏工具':'显示工具'}}</el-button>
       <el-button
        type="primary"
        plain
        size="small"
        @click="showWuman=!showWuman"
      >{{showWuman?'隐藏女眷':'显示女眷'}}</el-button>
      <template v-if="!isLocal">
        <el-button type="primary" plain size="small"  v-print="'#printMed'">打印</el-button>
        <el-button type="primary" plain size="small" @click="share()">分享</el-button>
      </template>
      <div class="search">
        <el-input placeholder="请输入名字" size="small" v-model="filterText"></el-input>
      </div>
    </el-row>
    <div class="tree-w" id="printMed">
      <el-tree
        ref="tree"
        :data="list"
        :load="loadNode"
        lazy
        node-key="_id"
        :default-expand-all="true"
        @node-drop="handleDrop"
        :filter-node-method="filterNode"
        draggable
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span class="name" :class="{wuman:data.gender == 2}">{{ data.name }}</span>
          <span v-show="showTools">
            <el-button
              type="text"
              size="mini"
              icon="el-icon-circle-plus-outline"
              title="新增"
              @click="add(data._id)"
            ></el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              title="编辑和查看"
              @click="edit(data)"
            ></el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-view"
              title="以此为节点打开"
              @click="open(data._id)"
            ></el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-delete"
              title="删除"
              @click="remove( data,node)"
            ></el-button>
          </span>
        </span>
      </el-tree>
    </div>
  </div>
</template>
<script>
export default {
  name: "home",
  data() {
    return {
      count: 1,
      parent: this.$route.query.parent || -1,
      list: [],
      showTools: true,
      filterText:"",
      showWuman:true, // 显示隐藏女眷
      mobile: this.$utils.isMobile,
      isLocal: process.env.NODE_ENV == "local"
    };
  },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      showWuman(){
        this.$refs.tree.filter();
      }
    },
  async mounted() {
    let list = await this.getList();
    this.list = this.handle(list);
  },
  methods: {
    handle(list){
      // 兼容
        for(let i = 0; i < list.length; i++){
          let item = list[i];
          if(item.ID){
              item._id = item.ID;
          }
        }
        return list;
    },
    async getList(params) {
      params = params || {};
      if (!params.parent) {
        params.parent = this.parent;
      }
      let list = await this.$api.personList(params);
      this.handle(list);
      return Promise.resolve(list);
    },
    filterNode(value, data){
       if(data.gender == 2 && !this.showWuman){
          return false;
        }

        if(!value){
            return true;
        }
        
        return data.name.indexOf(value) !== -1;
    },
    back() {
      if (window.history.length > 1) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: "home" });
      }
    },
    add(parent) {
      this.$router.push({
        name: "add",
        query: { parent: parent || this.parent }
      });
    },
    edit(data) {
      this.$router.push({
        name: "add",
        query: { parent: data.parent, id: data._id }
      });
    },
    open(parent) {
      let path = this.$route.path;
      if (parent) {
        window.location.href = `${path}?parent=${parent}`;
      } else {
        window.location.href = `${path}`;
      }
    },
    async handleDrop(draggingNode, dropNode, dropType, ev) {
        let node = draggingNode.data;
        let orders = [];
        if (dropType == "inner") {
          node.parent = dropNode.data._id;
          node.order = 0;
          
        } else {
         let pNode = dropNode.parent
          if (dropNode.parent) {
            let d = pNode.data;
            if (Array.isArray(d)) {
              node.parent = -1;
            } else {
              node.parent = d._id;
            }
            let childNodes = pNode.childNodes || [];
            for(let i = 0; i < childNodes.length; i++){
               let item = childNodes[i];
               if(item.data.order != i){
                 console.log(item.data.name);
                 orders.push({
                   id:item.data._id,
                   order:i
                 });
                 item.data.order = i;
               }
            }
          } else {
            console.error("错误操作",dropNode)
          }
        }
        await this.$api.editPerson({ parent: node.parent, id: node._id });
        await this.$api.updateOrders({list:orders})
        this.$message.success("更新节点成功")
    },
    allowDrop(draggingNode, dropNode, type) {
      return true;
    },
    allowDrag(draggingNode) {
      return true;
    },
    async loadNode(node, resolve) {
      let data = node.data || {};
      let childs = data.childs || 0;
      let id = data._id;
      if (childs <= 0 || !id) {
        resolve([]);
      } else {
        let list = await this.getList({ parent: id });
        this.handle(list);
        resolve(list);
      }
    },
    async remove(data, node) {
      let id = data._id;
      try {
        await this.$confirm("删除后不可恢复, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        await this.$api.delPerson({ id });
        this.$message.success("删除成功");
        this.$refs.tree.remove(node);
      } catch (e) {
        console.log(e);
      }
    },
    share(){
        let userinfo = this.$store.state.userinfo;
        if(userinfo){
            this.$router.push({name:"preview",params:{uid:userinfo._id}})
        }
    }
  }
};
</script>
<style scoped lang="scss">
.home {
  .search {
    float: right;
    white-space: nowrap;
    .el-input {
      margin-right: 6px;
    }
  }
  .tree-w{
      margin-top: 10px;
      padding: 10px;
      border: 1px dashed #ddd;
  }
  .wuman{
    color: #fcc3c3;
  }
}
.home.mobile{
  .search{
    float: none;
    margin-top: 6px;
  }
}
</style>
<style lang="scss" >
.home {
  .custom-tree-node {
    span.name {
      padding-right: 6px;
    }
  }
}
</style>